{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 计算之比特位宽\n",
    "\n",
    "参考：[计算之比特位宽](https://chenzomi12.github.io/02Hardware01Foundation/06BitWidth.html)\n",
    "\n",
    "数据比特位宽是C++中非常重要的概念，理解它对于内存优化、位运算以及底层编程都很关键。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```{admonition} 比特与字节\n",
    "- **比特（bit）**：计算机最小存储单位，只有 0 或 1 两种状态。\n",
    "- **字节（Byte）**：由 8 个比特组成（`1Byte = 8bit`）。\n",
    "- **字长（Word）**：CPU 一次能处理的数据宽度（如 32位 / 64位系统）。\n",
    "```\n",
    "\n",
    "## C++ 基本数据类型的位宽**\n",
    "不同数据类型占用的比特数不同，可通过 `sizeof()` 查看字节数（需乘以 8 转换为比特）。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "bool: 8 bits\n",
      "char: 8 bits\n",
      "int: 32 bits\n",
      "float: 32 bits\n",
      "double: 64 bits\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "@0x7f2d49185ca0"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#include <iostream>\n",
    "using namespace std;\n",
    "\n",
    "cout << \"bool: \" << sizeof(bool) * 8 << \" bits\" << endl;       // 通常 8 位\n",
    "cout << \"char: \" << sizeof(char) * 8 << \" bits\" << endl;       // 8 位\n",
    "cout << \"int: \" << sizeof(int) * 8 << \" bits\" << endl;         // 通常 32 位\n",
    "cout << \"float: \" << sizeof(float) * 8 << \" bits\" << endl;     // 32 位\n",
    "cout << \"double: \" << sizeof(double) * 8 << \" bits\" << endl;   // 64 位"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 位宽与数值范围的关系\n",
    "数据类型的位宽决定了其能表示的数值范围。例如：\n",
    "- **无符号整数（`unsigned`）**：$n$ 位可表示 $0$ 到 $2^n-1$。\n",
    "- **有符号整数**：$n$ 位可表示 $-2^{n-1}$ 到 $2^{n-1} - 1$（补码表示）。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**示例**：\n",
    "- `unsigned char`（8位）：范围 `0` 到 `255`（$2^8-1$）。\n",
    "- `int`（32位）：范围 $-2,147,483,648$ 到 $2,147,483,647$|。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 位运算操作\n",
    "位运算直接操作数据的二进制位，常用运算符：\n",
    "- `&`（按位与）、`|`（按位或）、`^`（按位异或）、`~`（取反）。\n",
    "- `<<`（左移）、`>>`（右移）。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**示例：提取比特位**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "第2位是: 1\n"
     ]
    }
   ],
   "source": [
    "unsigned int num = 21;  // 二进制: 0001 0101\n",
    "bool bit2 = (num & (1 << 2)) != 0;  // 提取第2位（从0开始）\n",
    "cout << \"第2位是: \" << (bit2 ? \"1\" : \"0\") << endl; "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 位域（Bit Fields）\n",
    "\n",
    "用于在结构体中精确控制成员变量占用的比特数，节省内存。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "红色值: 30\n"
     ]
    }
   ],
   "source": [
    "struct Color {\n",
    "    unsigned int red : 5;    // 5位，范围0-31\n",
    "    unsigned int green : 6;  // 6位，范围0-63\n",
    "    unsigned int blue : 5;   // 5位，范围0-31\n",
    "};\n",
    "\n",
    "Color c = {30, 60, 28};\n",
    "cout << \"红色值: \" << c.red << endl;"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 底层编程应用\n",
    "- **内存对齐**：编译器可能会插入填充字节以对齐数据，影响实际内存占用。\n",
    "- **位掩码（Bitmask）**：用于标志位的组合，例如："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "enum Flags {\n",
    "    READ = 1,    // 0001\n",
    "    WRITE = 2,   // 0010\n",
    "    EXECUTE = 4  // 0100\n",
    "};\n",
    "\n",
    "int permissions = READ | WRITE;  // 组合标志：0011\n",
    "bool canWrite = (permissions & WRITE) != 0;  // 检查标志"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "C++14",
   "language": "C++14",
   "name": "xcpp14"
  },
  "language_info": {
   "codemirror_mode": "text/x-c++src",
   "file_extension": ".cpp",
   "mimetype": "text/x-c++src",
   "name": "c++",
   "version": "14"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
